import { DataString, empty } from "../data.mts";
import { tsToString } from "../utilities.mjs";

const query = async () => {
  const data = await cookieStore.getAll();
  let result = 0;
  for (const cookie of data) {
    result += cookie.name?.length ?? 0;
    result += cookie.value?.length ?? 0;
    result += cookie.domain?.length ?? location.hostname.length;
    result += cookie.path?.length ?? 1;
    result += cookie.expires ? String(cookie.expires).length : 0;
    result += cookie.sameSite?.length ?? 3;
  }
  return { count: data.length, result, data };
};

const clear = async () => {
  const cookies = await cookieStore.getAll();
  for (const cooky of cookies) {
    const cookieName = cooky.name;
    if (cookieName) {
      await cookieStore.delete(cookieName);
    }
  }
};

const remove = async (cookieName: string) => {
  await cookieStore.delete(cookieName);
};

const change = async (cookie: CookieInit) => {
  await cookieStore.set(cookie);
};

const summary = (
  data: Awaited<ReturnType<typeof query>>,
) => `${DataString.Cookie}：
数量 ${String(data.count)}
大小 ${String(data.result)}`;

const stringify = (
  cookie: CookieListItem,
  withValue = true,
) => `键：${cookie.name ?? empty}${
  withValue
    ? `
值：${cookie.value ?? empty}`
    : ""
}
作用域名：${cookie.domain ?? empty}
作用路径：${cookie.path ?? empty}
过期时间：${typeof cookie.expires == "number" ? tsToString(cookie.expires) : empty}
SameSite：${cookie.sameSite ?? "lax"}
HTTPS：${cookie.secure ? "是" : "否"}
分区：${cookie.partitioned ? "是" : "否"}`;

export default { query, clear, remove, change, stringify, summary };
